﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;

public partial class MyUsers : System.Web.UI.Page
{
    List<_User> _userList = new List<_User>();

    readonly SqlConnection _conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if(Request.IsAuthenticated==false)
        {
            Response.Redirect("Login.aspx");
        }
        if (Request.IsAuthenticated)
        {
            string n = "";
            var sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", _conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            _conn.Open();
            var dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            _conn.Close();

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData();
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }
    }

    public string MD5String(string input)
    {
        var md5 = new MD5CryptoServiceProvider();
        byte[] inputBytes = Encoding.ASCII.GetBytes(input);
        byte[] hashBytes = md5.ComputeHash(inputBytes);
        var sb = new StringBuilder();
        foreach (byte t in hashBytes)
        {
            sb.Append(t.ToString("x2"));
        }
        return sb.ToString();
    }

    private void SetData()
    {
        user_list.DataSource = _User.SelME(User.Identity.Name);
        user_list.DataBind();

        _userList = _User.SelUser(User.Identity.Name);
        if (_userList.Count == 0)
        {
            message.Visible = true;
        }
        else
        {
            message.Visible = false;
            My_user_list.DataSource = _userList;
            My_user_list.DataBind();
        }
    }

    private void SetPOPupData()
    {
        FillDDL.Fill_Licence_Type(DropLicence);
    }

    public void AddUser()
    {
        modal_message_user.Text = "&nbsp";
        lit_add_user.Text = "Add new user!";
        lblMainUser_id.Text = User.Identity.Name;
        lblMainUser.Text = "";
        lbluser_id.Text = "";
        lblUserEdit.Text = "";
        tb_name.Text = "";
        tb_secondname.Text = "";
        tb_login.Text = "";
        tb_password.Text = "";
        tb_email.Text = "";
        DropLicence.SelectedIndex = -1;
        check_superuser.Checked = false;
        check_activated.Checked = false;
        check_additional_user.Checked = false;
    }

    public void EditUser(int userId)
    {
        lblUserEdit.Text = "Edit";
        modal_message_user.Text = "&nbsp";
        lit_add_user.Text = "Edit user!";
        lbluser_id.Text = userId.ToString();
        tb_name.Text = _User.EditUser(userId)._Name;
        tb_secondname.Text = _User.EditUser(userId)._SecondName;
        tb_login.Text = _User.EditUser(userId)._Login;
        tb_password.Text = "";
        tb_email.Text = _User.EditUser(userId)._Email;
        DropLicence.SelectedValue = _User.EditUser(userId)._ID_Licence.ToString();
        check_superuser.Checked = _User.EditUser(userId)._Superuser;
        check_activated.Checked = _User.EditUser(userId)._Activated;
        check_additional_user.Checked = _User.EditUser(userId)._Additional_user;
    }

    protected void My_user_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            var userId = e.Item.FindControl("idLabel") as Label;
            if (userId != null)
            {
                lbluser_id.Text = userId.Text;
                lblUserEdit.Text = "Edit";
                lblMainUser.Text = "";
                SetPOPupData();
                EditUser(Convert.ToInt32(userId.Text));
            }
            Modal_Popup_New_User.Show();
        }

        if (e.CommandName == "Delete")
        {
            var userId = e.Item.FindControl("idLabel") as Label;
            if (userId != null)
            {
                lbl_userID.Text = userId.Text;
                Modal_Popup_Delete.Show();
            }
        }
    }

    protected void My_user_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("idL").Visible = false;
    }

    protected void My_user_list_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
    {
        var myUserListPage = (My_user_list.FindControl("My_users_list_Page")) as DataPager;
        if (myUserListPage != null) myUserListPage.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
        SetData();
    }

    protected void My_user_list_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {

    }
    protected void My_user_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }

    protected void user_list_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("idL").Visible = false;
    }

    protected void user_list_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName == "Edit")
        {
            var userId = e.Item.FindControl("my_idLabel") as Label;
            if (userId != null)
            {
                lbluser_id.Text = userId.Text;
                lblMainUser.Text = "MainUser";
                SetPOPupData();
                EditUser(Convert.ToInt32(userId.Text));
            }
            Modal_Popup_New_User.Show();
        }
    }

    protected void user_list_ItemEditing(object sender, ListViewEditEventArgs e)
    {

    }

    protected void bt_add_user_Click(object sender, EventArgs e)
    {
        AddUser();
        SetPOPupData();
        Modal_Popup_New_User.Show();
    }

    protected void bt_adduser_cancel_Click(object sender, EventArgs e)
    {
        Modal_Popup_New_User.Hide();
    }
    protected void bt_adduser_Click(object sender, EventArgs e)
    {
        modal_message_user.Text = "&nbsp";
        modal_message_user.ForeColor = System.Drawing.Color.White;
        if (lblUserEdit.Text == "Edit")
        {
            if (lblMainUser.Text == "MainUser")
            {
                try
                {
                    var selCmdLogin = new SqlCommand("SELECT login FROM users WHERE login=@login and id<>@id", _conn);
                    selCmdLogin.Parameters.Add(new SqlParameter("@login", SqlDbType.NVarChar)).Value = tb_login.Text;
                    selCmdLogin.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar)).Value = lbluser_id.Text;
                    _conn.Open();
                    SqlDataReader dr = selCmdLogin.ExecuteReader();
                    if (dr.HasRows)
                    {
                        if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                        {
                            modal_message_user.Text = "Error! Login exists!";
                            modal_message_user.ForeColor = System.Drawing.Color.Red;
                        }
                        _conn.Close();
                    }
                    else
                    {
                        _User.UpdateME(lbluser_id.Text, tb_name.Text, tb_secondname.Text, tb_login.Text,
                            MD5String(tb_password.Text), tb_email.Text, DropLicence.SelectedValue,
                            check_superuser.Checked.ToString(), check_activated.Checked.ToString(),
                            check_additional_user.Checked.ToString());
                        if (modal_message_user.ForeColor != System.Drawing.Color.Green)
                        {
                            modal_message_user.Text = "Saved!";
                            modal_message_user.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                }
                catch
                {
                    if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                    {
                        modal_message_user.Text = "Error updating data!";
                        modal_message_user.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
            else
            {
                try
                {
                    var selCmdLogin = new SqlCommand("SELECT login FROM users WHERE login=@login and id<>@id", _conn);
                    selCmdLogin.Parameters.Add(new SqlParameter("@login", SqlDbType.NVarChar)).Value = tb_login.Text;
                    selCmdLogin.Parameters.Add(new SqlParameter("@id", SqlDbType.NVarChar)).Value = lbluser_id.Text;
                    _conn.Open();
                    var dr = selCmdLogin.ExecuteReader();
                    if (dr.HasRows)
                    {
                        if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                        {
                            modal_message_user.Text = "Error! Login exists!";
                            modal_message_user.ForeColor = System.Drawing.Color.Red;
                        }
                        _conn.Close();
                    }
                    else
                    {
                        _User.Update(lbluser_id.Text, tb_name.Text, tb_secondname.Text, tb_login.Text, MD5String(tb_password.Text), tb_email.Text, DropLicence.SelectedValue, check_superuser.Checked.ToString(), check_activated.Checked.ToString(), check_additional_user.Checked.ToString(), User.Identity.Name);
                        if (modal_message_user.ForeColor != System.Drawing.Color.Green)
                        {
                            modal_message_user.Text = "Saved!";
                            modal_message_user.ForeColor = System.Drawing.Color.Green;
                        }
                    }
                    dr.Close();
                }
                catch
                {
                    if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                    {
                        modal_message_user.Text = "Error updating data!";
                        modal_message_user.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }
        else
        {
            try
            {
                var selCmdLogin = new SqlCommand("SELECT login FROM users WHERE login=@login", _conn);
                selCmdLogin.Parameters.Add(new SqlParameter("@login", SqlDbType.NVarChar)).Value = tb_login.Text;
                _conn.Open();
                var dr = selCmdLogin.ExecuteReader();
                if (dr.HasRows)
                {
                    if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                    {
                        modal_message_user.Text = "Error! Login exists!";
                        modal_message_user.ForeColor = System.Drawing.Color.Red;
                    }
                    _conn.Close();
                }
                else
                {
                    _User.Insert(tb_name.Text, tb_secondname.Text, tb_login.Text, MD5String(tb_password.Text), tb_email.Text, DropLicence.SelectedValue, check_superuser.Checked.ToString(), check_activated.Checked.ToString(), check_additional_user.Checked.ToString(), User.Identity.Name);
                    var sCmdMaxUserId = new SqlCommand("SELECT MAX(id) FROM users WHERE MAIN_USER=@MAIN_USER", _conn);
                    sCmdMaxUserId.Parameters.Add(new SqlParameter("@MAIN_USER", SqlDbType.Int)).Value = User.Identity.Name;
                    _conn.Close();
                    _conn.Open();
                    lbluser_id.Text = Convert.ToString(sCmdMaxUserId.ExecuteScalar());
                    _conn.Close();
                    EditUser(Convert.ToInt32(lbluser_id.Text));
                    if (modal_message_user.ForeColor != System.Drawing.Color.Green)
                    {
                        modal_message_user.Text = "Saved!";
                        modal_message_user.ForeColor = System.Drawing.Color.Green;
                    }
                }
                dr.Close();
            }
            catch
            {
                if (modal_message_user.ForeColor != System.Drawing.Color.Red)
                {
                    modal_message_user.Text = "Error saving data!";
                    modal_message_user.ForeColor = System.Drawing.Color.Red;
                }
            }
        }
    }

    protected void bt_delete_user_Click(object sender, EventArgs e)
    {
        _User.DeleteUser(Convert.ToInt32(lbl_userID.Text));
        SetData();
    }
    protected void bt_delete_cancel_Click(object sender, EventArgs e)
    {
        Modal_Popup_Delete.Hide();
    }
}
